package com.joecy.config;

import com.netflix.zuul.ZuulFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 陈玉林
 * @modifiedBy:
 * @date: Create In 15:51 2018/10/23
 * @description:
 */
//使该类成为配置类,注入spring容器
@Configuration
public class MyZuulFilter extends ZuulFilter {

    /**
     * pre：在请求路由之前执行过滤。我们可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等。
     * route：这种过滤器将请求路由到微服务。这种过滤器用于构建发送给微服务的请求，并使用Apache HttpClient或Netfilx Ribbon请求微服务。
     * post：这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。
     * error：在其他阶段发生错误时执行该过滤器。
     * 除了默认的过滤器类型，Zuul还允许我们创建自定义的过滤器类型。例如，我们可以定制一种STATIC类型的过滤器，直接在Zuul中生成响应，而不将请求转发到后端的微服务。
     * to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,
     * "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.
     * We also support a "static" type for static responses see  StaticResponseFilter.
     * Any filterType made be created or added and run by calling FilterProcessor.runFilters(type)
     *
     * @return A String representing that type
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 必须定义过滤器顺序，如果该过滤器的优先级不是很重要，过滤器顺序命令可以相同，过滤器命令不需要是连续的。
     * 命令从0,1,2...优先级依次降低
     * filterOrder() must also be defined for a filter. Filters may have the same  filterOrder if precedence is not
     * important for a filter. filterOrders do not need to be sequential.
     * @return the int order of a filter
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 返回true run()方法将要执行，false将不执行，可以作为run() 方法执行开关。
     * a "true" return from this method means that the run() method should be invoked
     * @return true if the run() method should be invoked. false will not invoke the run() method
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 可以自己编写任意的业务逻辑
     * if shouldFilter() is true, this method will be invoked. this method is the core method of a ZuulFilter
     * @return Some arbitrary artifact may be returned. Current implementation ignores it.
     */
    @Override
    public Object run() {
        System.out.println("shouldFilter() is true");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestURL = request.getRequestURL().toString();
        int index = requestURL.lastIndexOf('/')+1;
        String username = requestURL.substring(index);
        //判定长度小于三为非法用户名
        if (username.length() >2 ) {
            return true;
        }else{
            throw new RuntimeException("非法用户名，请检查！");
        }
    }
}
